<?php

namespace App\Http\Controllers\supplier;

use App\Http\Controllers\Controller;
use App\Http\Requests\SupplierAuthentication;
use App\Http\Requests\SupplierRegister;
use App\Models\Admin\Config;
use App\Models\Admin\SupplierAuthenticationAuditRecord;
use App\Models\Admin\SupplierConfiguration;
use App\Models\Admin\SupplierSmsConfig;
use App\Models\Mysql\XnSupplierGoods;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Admin\Supplier;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Guid\Guid;
use Throwable;
use Qiniu\Auth;
use Illuminate\Support\Facades\Redis;
class SupplierLogonController extends Controller
{
    //登陆发送短信
    public function sendSms_login(Request $request){
        $params = $request->all();
        if (empty($params['phone'])) {
            return $this->sendError('参数传递错误');
        }
        $phone          = $params['phone'];//手机号
        $code           = rand(0000,9999);//验证码
        $signName       = SupplierSmsConfig::query()->where(['sid'=>$this->supplier_id(),'state'=>1])->value('signName');//模板签名
        $templatecode    = SupplierSmsConfig::query()->where(['sid'=>$this->supplier_id(),'state'=>1])->value('templateCode');//模板code

        $respond_code   = SmsController::sendSms($phone,$code,$signName,$templatecode);
        Redis::setex('login'.$phone,$code,300);
        if (!$respond_code){
            return $this->sendError('短信发送失败');
        }

        return  $this->sendResponse([],'短信发送成功');
    }

    /**
     * 供应商注册
     *
     * @param SupplierRegister $request
     * @return JsonResponse
     */
    public function register(SupplierRegister $request): JsonResponse
    {
        $params = $request->validated();
        // 注册用户
        DB::beginTransaction();
        try {
            $supplier = new Supplier();
            $supplier->phone = $params['phone'];
            $supplier->id_number = $params['id_number'];
            $supplier->actual_name = $params['actual_name'];
            $supplier->company_name = $params['company_name'];
            $supplier->login_password = password_hash($params['login_password'], PASSWORD_DEFAULT);
            $supplier->business_number = Supplier::businessNumberCreate();
            $supplier->business_license_number = $params['business_license_number'];
            if (!$supplier->save()) {
                throw new Exception("供应商添加失败");
            }
            $config = new SupplierConfiguration();
            $config->private_key = md5(Guid::fromDateTime(new \DateTime())->toString());
            $config->sid = $supplier->id;
//            $config->domain = $params['domain'];
            // TODO 数据库配置 实际到时候需要生成 这里先定死了

            if (!$config->save()) {
                throw new Exception("供应商配置添加失败");
            }
            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();
            Log::error("供应商注册添加失败:" . $e->getMessage(), [
                'params'    => $params,
                'error'     => error2array($e),
            ]);
            return $this->sendError('注册失败');
        }
        return $this->sendResponse([],'注册成功');
    }

    //判断手机号是否已经注册
    public function is_phones(Request $request){
        $params = $request->all();
        if (empty($params['phone'])){
            return $this->sendError('请输入手机号');
        }
        if ($this->is_phone($params['phone']) == false){
            return $this->sendError('请输入正确的手机号码');
        }

        $res  =Supplier::where('phone',$params['phone'])->first();
        if (!empty($res)){
            return $this->sendError('手机号已被注册');
        }
        return $this->sendResponse([],'验证通过');
    }
    //供应商忘记密码
    public function no_password(Request $request)
    {
        $params = $request->all();
        if (empty($params['phone'])){
            return $this->sendError('请输入手机号');
        }
        if (empty($params['code'])){
            return $this->sendError('请输入验证码');
        }
        if (!$this->is_phone($params['phone'])){
            return $this->sendError('请输入正确的手机号码');
        }
        $phone          = $params['phone'];
        $code           = $params['code'];

//        //验证验证码
//        $redis          = new \redis();
//        $redis->connect('127.0.0.1',6379);//连接redis
//
//        $value  = $redis->get('supplier_logon'.$phone);
//
//        if (empty($value)) {
//            return $this->sendError('验证码已失效');
//        }
//        if ($value != $code) {
//            return $this->sendError('验证码错误');
//        }
//        $redis->del('supplier_logon'.$phone);
        $res = Supplier::where('phone',$params['phone'])->update(['login_password'=>password_hash($params['login_password'], PASSWORD_DEFAULT)]);
        if (!$res){
            return $this->sendError('重置失败');
        }
        return $this->sendResponse([],'重置密码成功');
    }

    /**
     * 供应商信息认证
     *
     * @param SupplierAuthentication $request
     * @return JsonResponse
     */
    public function authentication(SupplierAuthentication $request): JsonResponse
    {
        $params = $request->validated();
        /** @var Supplier|null $supplier **/
        $supplier = Supplier::query()->find($params['supplier_id']);

        if (!$supplier) {
            return $this->sendError('供应商不存在');
        }
        // 更新
        DB::beginTransaction();
        try {
            if (!$supplier->update($params)) {
                throw new Exception("供应商信息更新失败");
            }
            $record = new SupplierAuthenticationAuditRecord();
            $record->sid = $supplier->id;
            $record->state = 0;
            if (!$record->fill($params)->save()) {
                throw new Exception("添加记录失败");
            }
            Supplier::where('id',$supplier->id)->update(['account_verification'=>0]);
            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();
            Log::error("供应商认证失败:" . $e->getMessage(), [
                'params'    => $params,
                'error'     => error2array($e)
            ]);
            return $this->sendError('提交失败');
        }
        return $this->sendResponse([],'提交成功');
    }
   //获取七牛token
    public function qiniuToken(Request $request)
    {
        $config = Config::groups( 'qiniu');

        if ($config->isEmpty()) {
            return $this->sendError('未配置七牛设置');
        }
        $auth = new Auth($config->get('accessKey'), $config->get('secretKey'));
        // 返回l
        return $this->sendResponse([
            'token' => $auth->uploadToken($config->get('bucket'), expires: 86400),
            'expire_time' => strtotime('+1 day'),2
        ],'获取成功');
    }
    //供应商认证信息详情
    public function authentication_info(){
        $user = auth('support')->user();
        $user->id_number = substr($user->id_number,0,5).'*****************'.substr($user->id_number,14,4);
        return $this->sendResponse($user,'获取成功');
    }


    //模拟登录过期
    public function aaaaa(){
        return '{"success":false,"message":"\u767b\u5f55\u4fe1\u606f\u5df2\u8fc7\u671f,\u8bf7\u91cd\u65b0\u767b\u5f55","data":{"need_login":true}}';
    }

    //测试--生成数据库
    public function mysql_test()
    {
       $mysqlName =  'localhost';
       $userName = 'root';
       $userPassword = 'cB8cFeLdib8GsrC4';
       //创建数据库
       $conn = mysqli_connect($mysqlName,$userName, $userPassword);
       //
        if(!$conn){
            die("Connection failed:".mysqli_connect_error());
        }
        $database = 'mysql_ceshiaaa';
        $sq1 ="CREATE DATABASE ".$database;
        if(mysqli_query($conn,$sq1)){
            echo "Database created successfully";
        } else {
            echo "Error creating database:".mysqli_error($conn);
        }
        //查询sql文件路径
        $filePath = database_path('schema/supplier-schema.sql');
        // 构建 bash 命令
        $command ="mysql -h $mysqlName -u $userName -p$userPassword $database < $filePath";
//        var_dump($command);
        $output = shell_exec($command);
        var_dump($output);
        if(!empty($output)){
            echo"执行出错";
        } else {
            echo"SQL 文件成功导入!";
        }
        mysqli_close($conn);
    }
}
